﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using DTO;
using BUS;
using Telerik.Web.UI;

namespace TVC_WEB.Admin.Page
{
    public partial class DetailProduct : System.Web.UI.Page
    {
        private string sErr = "";
        public string strUploadFolder;
        public string Username;
        public static int ContentLength;
        private string name_image = "";
        private bool iflag = false;
        private long inewid;
        private ArrayList arr_categoryid = new ArrayList();


        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                LoadCombo();
                LoadTreeView();
                //   LoadLookup("pro",radcbbPromote);
                //   LoadLookup("bra",radcbbbrand);
                ////   LoadLookup("mat", radcbbmaterial);
                //   LoadLookup("age", radcbbage);
                //   LoadLookup("use", radcbbusage);
                //   LoadLookup("occ", radcbbocc);
                if (Session["productid"] != null)
                {
                    hdProductID.Value = Session["productid"].ToString();
                    LoadData(Convert.ToInt32(Session["productid"]));
                    ProductsControl prod_control = new ProductsControl();
                    ProductsInfo prod_info = new ProductsInfo();
                    prod_info = prod_control.Get(Convert.ToInt64(hdProductID.Value), ref sErr);
                    //          ddownlistnew.SelectedValue = prod_info.IDCategory.ToString();
               //     Session["productid"] = null;
                }
                else
                {

                }

            }
        }

        protected void LoadLookup(String cate, RadComboBox radcbb)
        {
            LookupsControl lkctr = new LookupsControl();
            DataTable dt = lkctr.Get_datatable(cate, ref sErr);

            LookupsInfo inf = new LookupsInfo();


            if (dt.Rows.Count > 0)
            {
                radcbb.DataSource = dt;
                //      radcbbPromote.DataBind();
                radcbb.DataBind();

            }
        }
        protected void btReset_Click(object sender, EventArgs e)
        {
            Reset();
        }

        public void LoadCombo()
        {

            //CategoriesControl cat_control = new CategoriesControl();
            //DataTable dt = cat_control.GetLeafsCategories(ref sErr);
            //ddownlistnew.DataSource = dt;
            //ddownlistnew.DataTextField = "NameVN";
            //ddownlistnew.DataValueField = "ID";
            //ddownlistnew.DataBind();

        }

        private void LoadData(int strProductID)
        {
            //    ne = new Product(strLanguageID);
            ProductsInfo prod_info = new ProductsInfo();
            ProductsControl prod_control = new ProductsControl();


            strUploadFolder = "~/" + ConfigurationManager.AppSettings["UploadFolder"].ToString() + "Images/";
            //  ne.ProductID = strProductID;
            try
            {
                prod_info = prod_control.Get(Convert.ToInt64(strProductID), ref sErr);
                CategoryProductControl cateprctr = new CategoryProductControl();
                DataTable dt = cateprctr.GetALLIDCode(Convert.ToInt64(strProductID), ref sErr);
                arr_categoryid = GetCategoryProduct(dt);
                Loadtreebox(RadtvCategory.Nodes, arr_categoryid);
                SetDataToForm(prod_info);
            }
            catch (System.Exception e)
            {
                lblErr.Text = e.Message;
            }


        }

        private void SetDataToForm(ProductsInfo prod_info)
        {
            txtCode.Text = prod_info.Code;
            if (DropDownList1.SelectedValue == "en-US")
            {
                txtShortDesc.Content = prod_info.ShortDecribes;
                txtLongDesc.Content = prod_info.LongDecribes;
                txtname.Text = prod_info.Name;
                txtwarranty.Text = prod_info.Warranty;
                txtPromote.Text = prod_info.Promote;
                //prod_info.ShortDecribesVN =
                //    prod_info.LongDecribesVN =

            }
            else
            {
                txtShortDesc.Content = prod_info.ShortDecribesVN;
                txtLongDesc.Content = prod_info.LongDecribesVN;
                txtname.Text = prod_info.NameVN;
                txtwarranty.Text = prod_info.WarrantyVN;
                txtPromote.Text = prod_info.PromoteVN;
            }
            if (prod_info.Image == "")
                img.ImageUrl = strUploadFolder + "noimages.jpg";
            else
                img.ImageUrl = strUploadFolder + prod_info.Image;
            if (prod_info.Icon == "")
                imgIcon.ImageUrl = strUploadFolder + "noimages.jpg";
            else
                imgIcon.ImageUrl = strUploadFolder + prod_info.Image;
            rblIsViewed.SelectedValue = prod_info.Status.ToString();
            //txtname.Text = prod_info.NameVN;
            txtoldprice.Text = prod_info.OldPrice.ToString();
            txtnewprice.Text = prod_info.NewPrice.ToString();
            txtSkue.Text = prod_info.Skue;
            txtWeight.Text = prod_info.Weight;
            txtDimension.Text = prod_info.Dimension;
            //int iindex = radcbbage.FindItemIndexByValue(prod_info.Usage);
            //radcbbage.Items[iindex].Selected = true;
            //iindex = radcbbbrand.FindItemIndexByValue(prod_info.Brand);
            //radcbbbrand.Items[iindex].Selected = true;
            //iindex = radcbbocc.FindItemIndexByValue(prod_info.Occasion);
            //radcbbocc.Items[iindex].Selected = true;
            //iindex = radcbbPromote.FindItemIndexByValue(prod_info.Promote);
            //radcbbPromote.Items[iindex].Selected = true;
            //iindex = radcbbusage.FindItemIndexByValue(prod_info.Usage);
            //radcbbusage.Items[iindex].Selected = true;
            //     txtRate.Text = prod_info

            //  txtQuantity.Text = prod_info.Quantity.ToString();
            rblTypeViewed.SelectedValue = prod_info.TypeView == "1" ? "1" : "0";
            //rblBEN_C.SelectedValue = prod_info.BEN_C == "1" ? "1" : "0";
            //rblBEN_H.SelectedValue = prod_info.BEN_H == "1" ? "1" : "0";
            //rblBEN_S.SelectedValue = prod_info.BEN_S == "1" ? "1" : "0";
            //rblBEN_R.SelectedValue = prod_info.BEN_R == "1" ? "1" : "0";
            //rblBEN_F.SelectedValue = prod_info.BEN_F == "1" ? "1" : "0";
            txtCountPreview.Text = prod_info.CountPreview.ToString();
        }


        private void Reset()
        {
            txtSkue.Text = "";
            txtWeight.Text = "";
            txtDimension.Text = "";
            txtCode.Text = "";
            txtname.Text = "";
            txtLongDesc.Content = "";
            txtShortDesc.Content = "";
            //FCKeditor_short.Value = "";
            //FCKeditor_long.Value = "";
            img.ImageUrl = "/Uploads/Image/noimages.jpg";
            cbpic.Checked = false;
            txtnewprice.Text = "";
            txtoldprice.Text = "";
            hdProductID.Value = "";
            //    txtQuantity.Text = "0";
            txtPromote.Text = "";
            txtwarranty.Text = "0";
            txtCountPreview.Text = "0";
        }

        protected void SaveCategoryProduct(ArrayList a)
        {
            CategoryProductControl ctr = new CategoryProductControl();
            if (hdProductID.Value != "")
                ctr.DeleteByIDProduct(Convert.ToInt64(hdProductID.Value));
            for (int i = 0; i < a.Count; i++)
            {
                int temp = Convert.ToInt32(a[i]);
                CategoryProductInfo inf = new CategoryProductInfo();
                inf.IDProduct = Convert.ToInt64(hdProductID.Value);
                inf.IDCode = temp;
                if (!ctr.IsExist(inf.IDCode, inf.IDProduct))
                    ctr.Add(inf, ref sErr);

            }
        }

        protected void btSave_Click(object sender, EventArgs e)
        {
            ProductsInfo prod_info = new ProductsInfo();
            ProductsControl prod_control = new ProductsControl();
            if (hdProductID.Value != "")
            {
                prod_info = prod_control.Get(Convert.ToInt64(hdProductID.Value), ref sErr);
            }
            try
            {

                lblErr.Text = "";
                //        prod_info.IDCategory = Convert.ToInt32(ddownlistnew.SelectedValue);
                prod_info.Status = Convert.ToInt32(rblIsViewed.Text);
                if (DropDownList1.SelectedValue == "en-US")
                {
                    prod_info.ShortDecribes = txtShortDesc.Content;
                    prod_info.LongDecribes = txtLongDesc.Content;
                    prod_info.Name = txtname.Text;
                    prod_info.Warranty = txtwarranty.Text;
                    prod_info.Promote = txtPromote.Text;
                    //prod_info.ShortDecribesVN =
                    //    prod_info.LongDecribesVN =

                }
                else
                {
                    prod_info.ShortDecribesVN = txtShortDesc.Content;
                    prod_info.LongDecribesVN = txtLongDesc.Content;
                    prod_info.NameVN = txtname.Text;
                    prod_info.WarrantyVN = txtwarranty.Text;
                    prod_info.PromoteVN = txtPromote.Text;
                }
                prod_info.Code = txtCode.Text;
                //prod_info.Name = txtname.Text;
                prod_info.OldPrice = Convert.ToDouble(txtoldprice.Text == "" ? "0" : txtoldprice.Text);
                prod_info.NewPrice = Convert.ToDouble(txtnewprice.Text == "" ? "0" : txtnewprice.Text);
                if (FileUpload_image.FileName != "" && cbpic.Checked == false)
                    prod_info.Image = upload_file(prod_info.Code);
                else
                {
                    String[] s = img.ImageUrl.Split(new char[] { '/' });
                    prod_info.Image = s[s.Length - 1];
                }
                if (FileUpload_imageIcon.FileName != "" && cbpicIcon.Checked == false)
                    prod_info.Icon = upload_fileIcon(prod_info.Code);
                else
                {
                    String[] s = imgIcon.ImageUrl.Split(new char[] { '/' });
                    prod_info.Icon = s[s.Length - 1];
                }
                prod_info.CountPreview = Convert.ToInt32(txtCountPreview.Text == "" ? "0" : txtCountPreview.Text);

                prod_info.TypeView = rblTypeViewed.SelectedValue;
                //prod_info.BEN_C = rblBEN_C.SelectedValue;
                //prod_info.BEN_F = rblBEN_F.SelectedValue;
                //prod_info.BEN_H = rblBEN_H.SelectedValue;
                //prod_info.BEN_R = rblBEN_R.SelectedValue;
                //prod_info.BEN_S = rblBEN_S.SelectedValue;
                prod_info.Skue = txtSkue.Text;
                prod_info.Weight = txtWeight.Text;
                //prod_info.Age = radcbbage.SelectedValue;
                //prod_info.Brand = radcbbbrand.SelectedValue;
                //prod_info.Occasion = radcbbocc.SelectedValue;
                //prod_info.Promote = radcbbPromote.SelectedValue;

                //      prod_info.Quantity = Convert.ToInt32(txtQuantity.Text == "" ? "0" : txtQuantity.Text);
                //   prod_info.CreateDay = DateTime.Now;
                if (lblErr.Text == "")
                {
                    try
                    {
                        int id = -1;
                        if (hdProductID.Value != "")
                        {
                            //prod_info.ID = Convert.ToInt64(hdProductID.Value);
                            //ProductsInfo temp = new ProductsInfo();
                            //temp = prod_control.Get_Products((int)prod_info.ID, ref sErr);
                            //prod_info.CountPreview = temp.CountPreview;

                            sErr = prod_control.Update(prod_info);
                            lblErr.Text = "Cập nhật thành công...";
                            LoadData((int)prod_info.ID);
                        }
                        else
                        {

                            id = prod_control.Add(prod_info, ref sErr);
                            lblErr.Text = "Thêm mới thành công...";
                            hdProductID.Value = id.ToString();
                            //Reset();
                        }
                        arr_categoryid.Clear();
                        arr_categoryid = GetCatgoryChecked(RadtvCategory.Nodes, arr_categoryid);
                        SaveCategoryProduct(arr_categoryid);

                    }
                    catch (System.Exception ex)
                    {
                        lblErr.Text = ex.Message.ToString();
                    }
                }
            }
            catch (System.Exception ex)
            {
                lblErr.Text = ex.Message.ToString();
            }
        }

        protected string upload_file(String code)
        {
            FileUpload fupload = FileUpload_image.FindControl("FileUpload_image") as FileUpload;
            HttpPostedFile postFile = fupload.PostedFile;
            strUploadFolder = "~/" + ConfigurationManager.AppSettings["UploadFolder"].ToString() + "Images/";
            ContentLength = Convert.ToInt32(ConfigurationManager.AppSettings["ContentLength"].ToString());
            if (fupload.HasFile == true)
            {
                if (postFile.ContentLength < ContentLength)
                {
                    try
                    {
                        string[] s = fupload.FileName.Split(new char[] { '.' });

                        string filename = code + "." + s[s.Length - 1];
                        string strImagePath = Server.MapPath(strUploadFolder + filename);
                        fupload.SaveAs(strImagePath);
                        img.ImageUrl = strUploadFolder + filename;
                        name_image = filename;
                    }
                    catch (Exception ex)
                    {
                        lblErr.Text = ex.Message;
                    }
                }
                else
                {
                    lblErr.Text = "Vui lòng chọn file ảnh có kích thước nhỏ hơn 200kb";
                }

            }
            else
            {

                lblErr.Text = " file đã tồn tại"; //"Vui lòng chọn file ảnh có kích thước nhỏ hơn 200kb";
            }
            return name_image;
        }
        protected string upload_fileIcon(String code)
        {
            FileUpload fupload = FileUpload_imageIcon.FindControl("FileUpload_imageIcon") as FileUpload;
            HttpPostedFile postFile = fupload.PostedFile;
            strUploadFolder = "~/" + ConfigurationManager.AppSettings["UploadFolder"].ToString() + "Images/";
            ContentLength = Convert.ToInt32(ConfigurationManager.AppSettings["ContentLength"].ToString());
            if (fupload.HasFile == true)
            {
                if (postFile.ContentLength < ContentLength)
                {
                    try
                    {
                        string[] s = fupload.FileName.Split(new char[] { '.' });

                        string filename = code + "." + s[s.Length - 1];
                        string strImagePath = Server.MapPath(strUploadFolder + filename);
                        fupload.SaveAs(strImagePath);
                        imgIcon.ImageUrl = strUploadFolder + filename;
                        name_image = filename;
                    }
                    catch (Exception ex)
                    {
                        lblErr.Text = ex.Message;
                    }
                }
                else
                {
                    lblErr.Text = "Vui lòng chọn file ảnh có kích thước nhỏ hơn 200kb";
                }

            }
            else
            {

                lblErr.Text = " file đã tồn tại"; //"Vui lòng chọn file ảnh có kích thước nhỏ hơn 200kb";
            }
            return name_image;
        }

        protected void btCancel_Click(object sender, EventArgs e)
        {
            Session["productid"] = null;
            Response.Redirect("~/Admin/Page/Productpage.aspx");

        }

        protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (hdProductID.Value != "")
                LoadData(Convert.ToInt32(hdProductID.Value));
        }

        protected void radcbbPromote_ItemsRequested(object sender, Telerik.Web.UI.RadComboBoxItemsRequestedEventArgs e)
        {

        }

        protected void radcbbPromote_ItemDataBound(object sender, Telerik.Web.UI.RadComboBoxItemEventArgs e)
        {
            e.Item.Text = ((DataRowView)e.Item.DataItem)["Description"].ToString();
            e.Item.Value = ((DataRowView)e.Item.DataItem)["Code"].ToString();
        }

        protected ArrayList GetCatgoryChecked(RadTreeNodeCollection radtv, ArrayList a)
        {

            foreach (RadTreeNode node in radtv)
            {
                if (node.Checked)
                    a.Add(node.Value);
                if (node.Nodes.Count > 0)
                {
                    a = GetCatgoryChecked(node.Nodes, a);
                }
            }
            return a;
        }

        private void LoadTreeView()
        {

            CategoriesControl ctr = new CategoriesControl();
            DataTable dt = ctr.GetAll(ref sErr);
            RadtvCategory.DataFieldID = "ID";
            RadtvCategory.DataFieldParentID = "LinkedID";
            RadtvCategory.DataTextField = "NameVN";
            RadtvCategory.DataValueField = "ID";
            RadtvCategory.CheckBoxes = true;

            RadtvCategory.DataSource = dt;

            RadtvCategory.DataBind();

        }

        protected ArrayList GetCategoryProduct(DataTable dt)
        {
            ArrayList kq = new ArrayList();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                kq.Add(Convert.ToInt32(dt.Rows[i]["IDCode"].ToString()));
            }
            return kq;

        }

        protected void Loadtreebox(RadTreeNodeCollection radtv, ArrayList arr)
        {

            foreach (RadTreeNode node in radtv)
            {
                if (node.Nodes.Count > 0)
                    Loadtreebox(node.Nodes, arr);
                if (CheckExistedCategory(node.Value, arr))
                    node.Checked = true;
            }
        }

        protected Boolean CheckExistedCategory(String value, ArrayList arr)
        {
            Boolean flag = false;
            for (int i = 0; i < arr.Count; i++)
            {
                if (value == arr[i].ToString())
                    flag = true;
            }
            return flag;
        }

        protected void btAddImage_Click(object sender, EventArgs e)
        {
            
            Response.Redirect("~/Admin/Page/ProductListImage.aspx");
        }
    }
}
